package com.quanyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.api.APIResponse;
import com.quanyan.common.http.HttpClientUtils;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.user.model.vo.DoyenActivity;
import com.quanyan.user.model.vo.request.SmsInfo;
import com.quanyan.user.model.vo.response.RespCheckDarenAuth;
import com.quanyan.user.service.HttpClientService;
import net.sf.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Administrator on 2016/8/24.
 */
@Service
public class HttpClientServiceImpl implements HttpClientService {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientServiceImpl.class);

    //c端接口地址
    @Value("${c.address}")
    private String address;
    //更新用户信息通知c端地址
    @Value("${c.setPlayerLabel}")
    private String setPlayerLabel;
    //发送短信地址
    @Value("${c.sendSms}")
    private String sendSms;
    //动态条数和照片
    @Value("${c.dynamics}")
    private String dynamics;
    //竞拍信息和动态信息
    @Value("${c.auction}")
    private String auction;
    //用户关系信息
    @Value("${c.relation}")
    private String relation;
    //达人检测
    @Value("${c.checkDaren}")
    private String checkDaren;

    private final String userActivityUrl = "/daren/GetUserActivityList.api";

    private String activityUrl = "/daren/GetActivityListById.api";

    @Override
    public APIResponse sendSms(Integer adminUid,SmsInfo smsInfo){
        try {
            logger.info("开始发送短信");
            String url = address + sendSms;
            logger.info("短信地址{}",url);
            Map param = getJsonParam();
            param.put("administratorid",adminUid);
            param.put("smsInfo", JSONArray.fromObject(smsInfo));
            String json = GsonUtils.toJson(param);
            logger.info("参数{}",json);
            String result = HttpClientUtils.postJson(url, json, 2000, 2000);
            logger.info("返回结果{}",result);
            JSONObject obj = JSON.parseObject(result);
            if(200 == (Integer) obj.get("errcode"))
                return APIResponse.returnSuccess();
            else
                return APIResponse.returnFail("系统异常！");
        } catch (Exception e) {
            logger.error("系统异常！{}",e);
            return APIResponse.returnFail("系统异常！");
        }
    }


    /**
     * 用户信息更新回调
     * @param currentUid
     * @return
     */
    @Async
    @Override
    public void updateSetting(Integer currentUid,List<Integer> interests, Integer type, Integer state) {
        try{
            logger.info("开始回调C++接口");
            String url = address + setPlayerLabel;
            Map param = getJsonParam();
            param.put("currentUid",currentUid);
            if (type != null) {
                param.put("type",type);
            }
            if (state != null) {
                param.put("state",state);
            }
            if (interests != null) {
                param.put("interest_id",interests);

            }
            logger.info("接口地址：{},参数:{}",url,param.toString());
            String result = HttpClientUtils.postJson(url, JSON.toJSONString(param));
            logger.info("返回结果{}",result);
            JSONObject obj = JSON.parseObject(result);
            if(200 == (int) obj.get("errcode"))
                logger.error("c++更新用户资料回调成功：uid：【{}】,time：【{}】",currentUid,new Date());
            else
                logger.error("c++更新用户资料回调失败：uid：【{}】,time：【{}】",currentUid,new Date());
        }catch (Exception e){
            logger.error("c++更新用户资料回调超时失败：uid：【{}】,time：【{}】,【{}】",currentUid,new Date(),e);
        }
    }

    /**
     * 获取动态信息
     * @param uid
     * @param phNum
     * @return
     */
    @Override
    public String getDynamicsMsg(Integer uid, Integer phNum) throws Exception{
        Map paramMap = new HashMap();
        paramMap.put("userID",uid);
        paramMap.put("phNum",phNum);
        String json = GsonUtils.toJson(paramMap);
        String result = HttpClientUtils.postJson(address + dynamics, json,3000,5000);
        return result;
    }

    /**
     * 获取动态信息和竞拍信息
     * @param uid
     * @param phNum
     * @return
     * @throws Exception
     */
    @Override
    public String getAuctionAndDynamicsMsg(Integer uid, Integer phNum) throws Exception {
        Map paramMap = new HashMap();
        paramMap.put("userID",uid);
        paramMap.put("phNum",phNum);
        String json = GsonUtils.toJson(paramMap);
        String result = HttpClientUtils.postJson(address + auction, json,3000,5000);
        return result;
    }

    /**
     * 获取用户关系信息
     * @param currentUid
     * @param uid
     * @return
     * @throws Exception
     */
    @Override
    public String getUserRelationInfo(Integer currentUid, Integer uid) throws Exception {
        Map param = getJsonParam();
        //当前用户
        param.put("currentUid",uid);
        //目标用户
        param.put("uid",currentUid);
        String json = GsonUtils.toJson(param);
        String result = HttpClientUtils.postJson(address + relation, json, 2000, 2000);
        return result;
    }

    private Map getJsonParam(){
        Map param = new HashMap<>();
        param.put("ver","1.0");
        param.put("protocol_ver",1);
        return param;
    }


    public List<DoyenActivity> getDyActivity(List<Integer> lstActivityId){
      String requestUrl = this.address + this.activityUrl;
      List<DoyenActivity> lstDoyenActivity = new ArrayList<>();
      if(lstActivityId != null && lstActivityId.size() == 0)
          return lstDoyenActivity;
      try {
            Map param = getJsonParam();
            param.put("activity_id_list",lstActivityId);
            String result = HttpClientUtils.postJson(requestUrl, GsonUtils.toJson(param));
            JSONObject jsonObjectResult = JSON.parseObject(result);
            if(jsonObjectResult.get("errcode").equals(200)){
                JSONObject o = JSON.parseObject(jsonObjectResult.get("data").toString());
                List<DoyenActivity> lstDoyen = GsonUtils.jsonToList(o.get("activity_list").toString(),DoyenActivity.class);
                return lstDoyen;
            }
        } catch (Exception e) {
            logger.error("批量获取达人活动失败！{}",e);
        }
        return lstDoyenActivity;
    }

    /**
     * 登录检查是否为达人
     * @param type
     * @param account
     * @return
     */
    public RespCheckDarenAuth checkDarenAuth(int type,String account){
        Map param = new HashMap();
        param.put("account",account);
        param.put("type",type);
        String json = GsonUtils.toJson(param);
        String result = "";
        RespCheckDarenAuth response;
        try {
            result = HttpClientUtils.postJson(address + checkDaren, json, 2000, 2000);
            logger.info("请求返回结果：{}",result);
             response = GsonUtils.jsonStrToEntity(result,RespCheckDarenAuth.class);
            return response;
        } catch (Exception e) {
            logger.error("接口返回信息：{}；接口异常信息:{}; 异常时间：{}", result,e);
            response = new RespCheckDarenAuth();
            response.setErrmsg("接口异常");
            response.setErrcode(100);
            response.setRet(false);
            return response;
        }

    }

    /**
     * 获取可预约的达人
     *
     * @param uid
     * @return
     */
    @Override
    public DoyenActivity getDoyenActivity(Integer uid) {
        if (uid == null || uid <=0 ) {
            return null;
        }

        DoyenActivity doyenActivity = null;
        String requestUrl = this.address + this.userActivityUrl;
        try {
            Map param = getJsonParam();
            param.put("uid",uid);
            param.put("type",1);
            param.put("page",0);
            param.put("size",1);
            String result = HttpClientUtils.postJson(requestUrl, GsonUtils.toJson(param));
            JSONObject jsonObjectResult = JSON.parseObject(result);

            JSONObject o = JSON.parseObject(jsonObjectResult.get("data").toString());
            List<DoyenActivity> lstDoyen = GsonUtils.jsonToList(o.get("activity_list").toString(),DoyenActivity.class);
            if (lstDoyen != null && lstDoyen.size() > 0) {
                doyenActivity = lstDoyen.get(0);
            }

            return doyenActivity;
        } catch (Exception e) {
            logger.error("批量获取达人活动失败！{}",e);
            return null;
        }
    }
}
